//
//  HomepageViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/3.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "HomepageViewController.h"
#import "SDCycleScrollView.h"
#import "SortCollectionViewCell.h"
#import "HomepageListTopItem.h"
#import "HomepageTableViewCell.h"
#import "XBTextLoopView.h"
#import "GoodsListViewController.h"
#import "SalesGoodsListViewController.h"
#import "JiFenGoodsListViewController.h"
#import "NewsViewController.h"
#import "GoodsDetailViewController.h"
#import "GoodsModel.h"
#import "HomepageCouponCollectionViewCell.h"
#import "MessageViewController.h"
#import <ShareSDK/ShareSDK.h>
#import "AppDelegate.h"
#import <GLKit/GLKit.h>
#import <CoreMotion/CoreMotion.h>
#import "PanoramaController.h"
// 引入 JPush 功能所需头文件
#import "JPUSHService.h"

#define topSortNum 4 // top分类数
#define appId @"" // 版本更新appid

@interface HomepageViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,SDCycleScrollViewDelegate,HomepageTableViewCellDelegate,UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView; // 轮播图
@property (nonatomic, strong) NSMutableArray *netImages; // 网络图片数组
@property (nonatomic, strong) UICollectionView *sortCollectionView; // top分类collectionView
@property (nonatomic, strong) UICollectionView *couponCollectionView; // 优惠券collectionView
@property (nonatomic, strong) NSMutableArray *goodsListArray;
@property (nonatomic, strong) NSMutableArray *sortedGoodsListArray;
@property (nonatomic, strong) NSMutableArray *newsArray;
@property (nonatomic, strong) NSMutableArray *newsTextArray;
@property (nonatomic, strong) NSMutableArray *couponArray;
@property (nonatomic, strong) UITextField *searchTF;
@property (nonatomic, strong) NSString *imageUrl;
@property (nonatomic, strong) NSString *adUrl;

@property (nonatomic, strong) UIView *redPoint;

@end

@implementation HomepageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    
    // 回收键盘
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [self setNavBar];
    [self.view addSubview:self.tableView];
    [self getGoodsListData];
    [self getBannerData];
    
    [self getCouponData];
    [self getUnreadMessage];
    
    // 判断APP状态
    [self checkAppStatus];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getResault1:) name:@"messageRead" object:nil];
}
- (void)getResault1:(NSNotification *)aNotification
{
    [self getUnreadMessage];
}
- (void)dealloc
{
    NSLog(@"注销通知");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"messageRead" object:nil];
}
- (void)checkAppStatus
{
    // APP状态，1 启用全部 2 仅启用苹果版 3 仅用启安卓版 0 锁定
    if ([[NSString stringWithFormat:@"%@",[UserDefaults valueForKey:@"appStatus"]] isEqualToString:@"1"] || [[NSString stringWithFormat:@"%@",[UserDefaults valueForKey:@"appStatus"]] isEqualToString:@"2"]) {
        
        [self Postpath]; // 检查版本更新
    } else if ([[NSString stringWithFormat:@"%@",[UserDefaults valueForKey:@"appStatus"]] isEqualToString:@"0"] || [[NSString stringWithFormat:@"%@",[UserDefaults valueForKey:@"appStatus"]] isEqualToString:@"3"]) {
        
        UIAlertController *alertController = [AlertHUD addAlertHUDWithMessage:@"您的APP服务已终止，请联系管理员" block:^{
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            UIWindow *window = app.window;
            
            window.alpha = 0;
            window.frame = CGRectMake(0, 0, 0, 0);
            exit(0);
        }];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}
#pragma mark - 获取未读消息数量
- (void)getUnreadMessage
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=smscount&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if ([responseObject[@"status"] intValue] == 1) {
            if ([responseObject[@"wdcount"] intValue] > 0) {
                self.redPoint.hidden = NO;
            } else {
                self.redPoint.hidden = YES;
            }
        } else {
            self.redPoint.hidden = YES;
            [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
#pragma mark - 获取优惠券
- (void)getCouponData
{
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/vouchers/vouchers.ashx?action=coupon&companyid=%@&pagesize=100000&pageindex=1",kServerURL,companyId] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        [self.tableView.mj_header endRefreshing];
        self.couponArray = [NSMutableArray array];
        if ([responseObject[@"status"] intValue] == 1) {
            
            NSArray *array = responseObject[@"list"];
            for (NSDictionary *dic in array) {
                [self.couponArray addObject:dic];
            }
        }
        NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:3];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        [self.couponCollectionView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
#pragma mark - 商品列表
- (void)getGoodsListData
{
    //    [MBProgressHUD showMessage:nil toView:self.view];
    //    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/content/content.ashx?action=list&companyid=%@&channelid=105&pagesize=100000&pageindex=1",kServerURL,companyId] parameters:nil success:^(id responseObject) {
    //        [MBProgressHUD hideHUDForView:self.view];
    //        [self.tableView.mj_header endRefreshing];
    //        self.goodsListArray = [NSMutableArray array];
    //        if ([responseObject[@"status"] intValue] == 1) {
    //            self.goodsListArray = [GoodsModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
    //            NSArray *array = responseObject[@"list"];
    //            for (NSDictionary *dic in array) {
    //                NSLog(@"---%@",dic[@"id"]);
    //            }
    //        }
    //        NSMutableArray *classNameArr = [NSMutableArray array];
    //        [self.goodsListArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    //            GoodsModel *model = obj;
    //            NSString *className1 = model.className;
    //            [classNameArr addObject:className1];
    //        }];
    //        //使用asset把classNameArr的数据去重
    //        NSSet *set = [NSSet setWithArray:classNameArr];
    //        NSArray *endClassNameArr = [set allObjects];
    //        // 排好序的数组
    //        self.sortedGoodsListArray = [NSMutableArray array];
    //
    //        // 遍历endClassNameArr把goodsListArray按照endClassNameArr里的id分成几个组,每个组都是空的数组
    //        [endClassNameArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    //            NSMutableArray *arr = [NSMutableArray array];
    //            [self.sortedGoodsListArray addObject:arr];
    //        }];
    //
    //        //遍历goodsListArray取其中每个学堂的id看看与endClassNameArr里的id匹配就把这个数据装到sortArray 对应的组中
    //        [self.goodsListArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    //            GoodsModel *model = obj;
    //
    //            for (NSString *str in endClassNameArr)
    //            {
    //                if([str isEqualToString:model.className])
    //                {
    //                    NSMutableArray *arr = [self.sortedGoodsListArray objectAtIndex:[endClassNameArr indexOfObject:str]];
    //
    //                    [arr addObject:model];
    //
    //                }
    //            }
    //        }];
    //        NSLog(@"---------------%@",self.sortedGoodsListArray);
    //        [self.tableView reloadData];
    //
    //    } failure:^(NSError *error) {
    //        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
    //        [self.tableView.mj_header endRefreshing];
    //    }];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/content/content.ashx?action=classcontent&companyid=%@&channelid=105&content_count=100000",kServerURL,companyId] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        [self.tableView.mj_header endRefreshing];
        self.sortedGoodsListArray = [NSMutableArray array];
        if ([responseObject[@"status"] intValue] == 1) {
            self.sortedGoodsListArray = [NSMutableArray arrayWithArray:responseObject[@"list"]];
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
#pragma mark - 新闻头条
- (void)getNewsData
{
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/content/content.ashx?action=list&companyid=%@&channelid=104&pagesize=100000&pageindex=1",kServerURL,companyId] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        [self.tableView.mj_header endRefreshing];
        self.newsArray = [NSMutableArray array];
        self.newsTextArray = [NSMutableArray array];
        if ([responseObject[@"status"] intValue] == 1) {
            self.newsArray = [GoodsModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            NSArray *array = responseObject[@"list"];
            for (NSDictionary *dic in array) {
                [self.newsTextArray addObject:dic[@"title"]];
            }
        }
        NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:2];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
#pragma mark - 获取轮播图
- (void)getBannerData
{
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/app/app.ashx?action=slide&companyid=%@",kServerURL,companyId] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        [self.tableView.mj_header endRefreshing];
        self.netImages = [NSMutableArray array];
        if ([responseObject[@"status"] intValue] == 1) {
            NSArray *array = responseObject[@"list"];
            for (NSDictionary *dic in array) {
                [self.netImages addObject:[NSString stringWithFormat:@"http:%@",dic[@"photoPath"]]];
            }
        }
        [self getNewsData];
        NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)setNavBar
{
    UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, SafeAreaTopHeight)];
    navBar.backgroundColor = UIColorWhite;
    [self.view addSubview:navBar];
    
    UIImageView *logoImg = [[UIImageView alloc] init];
    logoImg.image = UIImageNamed(logoName);
    [logoImg sizeToFit];
    [navBar addSubview:logoImg];
    [logoImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(navBar).offset(TopHeight+5);
        make.left.equalTo(navBar).offset(rateWidth(30));
    }];
    
    UIImageView *searchV = [[UIImageView alloc] init];
    searchV.image = UIImageNamed(@"searchbgimg");
    [searchV sizeToFit];
    [navBar addSubview:searchV];
    [searchV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(logoImg);
        make.left.equalTo(logoImg.mas_right).offset(rateWidth(30));
    }];
    searchV.userInteractionEnabled = YES;
    
    UITextField *searchTF = [[UITextField alloc] init];
    searchTF.font = UIFontSystem(13);
    searchTF.returnKeyType = UIReturnKeySearch;
    [searchV addSubview:searchTF];
    [searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchV).offset(rateWidth(60));
        make.size.mas_offset(CGSizeMake(rateWidth(300), rateHeight(55)));
        make.centerY.equalTo(searchV);
    }];
    searchTF.delegate = self;
    self.searchTF = searchTF;
    
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btn setImage:UIImageNamed(@"xinxi") forState:(UIControlStateNormal)];
    [btn sizeToFit];
    [navBar addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchV);
        make.right.equalTo(navBar).offset(-rateWidth(40));
    }];
    [btn addActionHandler:^{
        MessageViewController *messageVC = [[MessageViewController alloc] init];
        [self.navigationController pushViewController:messageVC animated:YES];
    }];
    UIView *redPoint = [[UIView alloc] init];
    redPoint.backgroundColor = [UIColor redColor];
    redPoint.layer.masksToBounds = YES;
    redPoint.layer.cornerRadius = 2.5;
    [navBar addSubview:redPoint];
    [redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(5, 5));
        make.left.equalTo(btn.mas_right).offset(-3);
        make.top.equalTo(btn).offset(1);
    }];
    self.redPoint = redPoint;
    self.redPoint.hidden = YES;
}
#pragma mark - 搜索
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (_searchTF.text.length != 0) {
        //        self.searchTF.text = @"";
        GoodsListViewController *goodsListVC = [[GoodsListViewController alloc] init];
        goodsListVC.classid = @"";
        goodsListVC.searchText = _searchTF.text;
        [self.navigationController pushViewController:goodsListVC animated:YES];
    } else {
        [TFHUD addRemindHUD:self.view message:@"请输入要搜索的内容"];
    }
    // 点击搜索按钮回收键盘
    [_searchTF resignFirstResponder];
    return YES;
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4+self.sortedGoodsListArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 3) {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        if (indexPath.section == 0) {
            // 轮播图
            if (_netImages.count != 0) {
                self.cycleScrollView.autoScroll = YES;
                [cell.contentView addSubview:self.cycleScrollView];
            }
        } else if (indexPath.section == 1) {
            // 分类
            [cell.contentView addSubview:self.sortCollectionView];
            
        } else if (indexPath.section == 2) {
            // 头条
            UIImageView *touTiaoImg = [[UIImageView alloc] init];
            touTiaoImg.image = UIImageNamed(@"toutiao");
            [touTiaoImg sizeToFit];
            [cell.contentView addSubview:touTiaoImg];
            [touTiaoImg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView);
                make.left.equalTo(cell.contentView).offset(rateWidth(30));
            }];
            WeakSelf
            if (self.newsTextArray.count != 0) {
                XBTextLoopView *loopView = [XBTextLoopView textLoopViewWith:self.newsTextArray loopInterval:3.0 initWithFrame:CGRectMake(rateWidth(190), 0, rateWidth(480), rateWidth(80)) selectBlock:^(NSString *selectString, NSInteger index) {
                    //                NSLog(@"%@===index%ld", selectString, index);
                    NewsViewController *newsVC = [[NewsViewController alloc] init];
                    [weakSelf.navigationController pushViewController:newsVC animated:YES];
                }];
                [cell.contentView addSubview:loopView];
            }
            
        } else if (indexPath.section == 3) {
            // 优惠券
            if (_couponArray.count != 0) {
                [cell.contentView addSubview:self.couponCollectionView];
            }
            
        }
        cell.selectionStyle = NO;
        return cell;
    } else {
        HomepageTableViewCell *cell = [[HomepageTableViewCell alloc] init];
        cell.delegate = self;
        //        NSArray *array = self.sortedGoodsListArray[indexPath.section-4];
        NSDictionary *dic = self.sortedGoodsListArray[indexPath.section-4];
        NSArray *array = dic[@"contentlist"];
        NSMutableArray *array1 = [GoodsModel mj_objectArrayWithKeyValuesArray:array];
        if (array1.count > 0) {
            if (array1.count < 5) {
                cell.itemArray = array1;
            } else {
                cell.itemArray = [array1 subarrayWithRange:NSMakeRange(0, 4)];
            }
            [cell.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.height.equalTo(@(rateWidth(440)*(int)ceil(cell.itemArray.count / 2.0)));
                make.width.equalTo(@(kScreenWidth));
                make.top.equalTo(cell.contentView);
                make.left.equalTo(cell.contentView);
            }];
        }
        cell.selectionStyle = NO;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return kScreenWidth/2;
    } else if (indexPath.section == 1) {
        return rateWidth(200);
    } else if (indexPath.section == 2) {
        return rateWidth(80);
    } else if (indexPath.section == 3) {
        if (_couponArray.count != 0) {
            return rateWidth(260);
        } else {
            return 0.01;
        }
        
    }
    else {
        if (self.sortedGoodsListArray.count > 0) {
            NSDictionary *dic = self.sortedGoodsListArray[indexPath.section-4];
            NSArray *array = dic[@"contentlist"];
            NSMutableArray *array1 = [GoodsModel mj_objectArrayWithKeyValuesArray:array];
            if (array1.count > 0) {
                if (array1.count > 2) {
                    //                    return rateWidth(440)*(int)ceil(array1.count / 2.0);
                    return rateWidth(440)*2;
                } else {
                    return rateWidth(440);
                }
            } else {
                return 0.01;
            }
        } else {
            return 0.01;
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == 1 || section == 2 || section == 3) {
        return 0.01;
    } else {
        if (self.sortedGoodsListArray.count > 0) {
            NSDictionary *dic = self.sortedGoodsListArray[section-4];
            NSArray *array = dic[@"contentlist"];
            NSMutableArray *array1 = [GoodsModel mj_objectArrayWithKeyValuesArray:array];
            if (array1.count > 0) {
                return rateWidth(80);
            } else {
                return 0.01;
            }
        } else {
            return 0.01;
        }
        
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.01;
    } else if (section == 1) {
        return rateWidth(2);
    } else if (section == 2) {
        return rateWidth(10);
    } else if (section == 3) {
        if (_couponArray.count != 0) {
            return rateWidth(10);
        } else {
            return 0.01;
        }
    }
    else {
        if (self.sortedGoodsListArray.count > 0) {
            NSDictionary *dic = self.sortedGoodsListArray[section-4];
            NSArray *array = dic[@"contentlist"];
            NSMutableArray *array1 = [GoodsModel mj_objectArrayWithKeyValuesArray:array];
            if (array1.count > 0) {
                return rateWidth(10);
            } else {
                return 0.01;
            }
        } else {
            return 0.01;
        }
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == 1 || section == 2 || section == 3) {
        return nil;
    } else {
        if (self.sortedGoodsListArray.count > 0) {
            NSDictionary *dic = self.sortedGoodsListArray[section-4];
            NSArray *array = dic[@"contentlist"];
            NSMutableArray *array1 = [GoodsModel mj_objectArrayWithKeyValuesArray:array];
            if (array1.count > 0) {
                HomepageListTopItem *item = [[HomepageListTopItem alloc] init];
                if (self.sortedGoodsListArray.count != 0) {
                    NSDictionary *dic = self.sortedGoodsListArray[section-4];
                    item.nameLB.text = dic[@"className"];
                }
                
                item.iconImg.image = UIImageNamed(@"xinpin");
                item.moreBtn.tag = section-4;
                
                // 更多
                [item.moreBtn addTarget:self action:@selector(moreGoodsList:) forControlEvents:(UIControlEventTouchUpInside)];
                
                return item;
            } else {
                return nil;
            }
        } else {
            return nil;
        }
        
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        NewsViewController *newsVC = [[NewsViewController alloc] init];
        [self.navigationController pushViewController:newsVC animated:YES];
    }
}
#pragma mark - 更多商品
- (void)moreGoodsList:(UIButton *)btn
{
    //    if (_sortedGoodsListArray.count != 0) {
    //        NSArray *array = _sortedGoodsListArray[btn.tag];
    //        GoodsModel *model = array[0];
    //        GoodsListViewController *goodsListVC = [[GoodsListViewController alloc] init];
    //        goodsListVC.classid = model.classid;
    //        [self.navigationController pushViewController:goodsListVC animated:YES];
    //    }
    if (self.sortedGoodsListArray.count != 0) {
        NSDictionary *dic = self.sortedGoodsListArray[btn.tag];
        GoodsListViewController *goodsListVC = [[GoodsListViewController alloc] init];
        goodsListVC.classid = [NSString stringWithFormat:@"%@",dic[@"classid"]];
        [self.navigationController pushViewController:goodsListVC animated:YES];
    }
}
#pragma mark - collectionview delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == _sortCollectionView) {
        return topSortNum;
    } else {
        return _couponArray.count;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _sortCollectionView) {
        SortCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"sortcollectionViewCell" forIndexPath:indexPath];
        cell.backgroundColor = kClearColor;
        NSArray *array1 = @[@"tuijian",@"liwu",@"tuijian",@"liwu"];
        NSArray *array2 = @[@"推荐商品",@"新品上架",@"促销秒杀",@"积分商城"];
        cell.iconImg.image = UIImageNamed(array1[indexPath.row]);
        cell.titleLB.text = array2[indexPath.row];
        
        return cell;
    } else {
        HomepageCouponCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"couponcollectionViewCell" forIndexPath:indexPath];
        cell.contentView.backgroundColor = UIColorWhite;
        if (indexPath.row%2 == 0) {
            cell.couponImg.image = UIImageNamed(@"couponHuang");
            [cell.lingQuBtn setTitleColor:globalOrange forState:(UIControlStateNormal)];
        } else {
            cell.couponImg.image = UIImageNamed(@"couponCheng"); // couponHuang
            [cell.lingQuBtn setTitleColor:UIColorWithRGB(248, 105, 70) forState:(UIControlStateNormal)];
        }
        // 赋值
        if (_couponArray.count != 0) {
            NSDictionary *dic = _couponArray[indexPath.row];
            cell.moneyLB.text = [NSString stringWithFormat:@"%@",dic[@"Qmoney"]];
            cell.conditionLB.text = dic[@"Atitle"];
        }
        return cell;
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _sortCollectionView) {
        return CGSizeMake(kScreenWidth/4, rateWidth(200));
    } else {
        return CGSizeMake(kScreenWidth/2, rateWidth(260));
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _sortCollectionView) {
        if (indexPath.row == 0 || indexPath.row == 1) {
            // 推荐商品 新品上架
            GoodsListViewController *goodsListVC = [[GoodsListViewController alloc] init];
            goodsListVC.type = indexPath.row+1;
            [self.navigationController pushViewController:goodsListVC animated:YES];
        } else if (indexPath.row == 2) {
            // 促销秒杀
            SalesGoodsListViewController *salesListVC = [[SalesGoodsListViewController alloc] init];
            [self.navigationController pushViewController:salesListVC animated:YES];
        } else if (indexPath.row == 3) {
            // 积分商城
            JiFenGoodsListViewController *jiFenListVC = [[JiFenGoodsListViewController alloc] init];
            [self.navigationController pushViewController:jiFenListVC animated:YES];
        }
    } else {
        // 优惠券领取
        if (_couponArray.count != 0) {
            NSDictionary *dic = _couponArray[indexPath.row];
            NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
            [MBProgressHUD showMessage:nil toView:self.view];
            [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/vouchers/vouchers.ashx?action=couponobtain&companyid=%@&code=%@&timestamp=%@&aid=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],dic[@"Aid"]] parameters:nil success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:self.view];
                
                if ([responseObject[@"status"] intValue] == 1) {
                    [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
                    
                } else {
                    [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
                }
                
            } failure:^(NSError *error) {
                [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
                
            }];
        }
    }
    
}
#pragma mark - collectionView 跳转
- (void)sendGoodsModel:(GoodsModel *)model
{
    GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
    goodsDetailVC.contentId = model.id;
    [self.navigationController pushViewController:goodsDetailVC animated:YES];
}
//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//    return UIEdgeInsetsMake(rateHeight(20), rateWidth(30), rateHeight(20), rateWidth(30));//分别为上、左、下、右
//}
#pragma mark - 轮播图
- (SDCycleScrollView *)cycleScrollView
{
    if (!_cycleScrollView) {
        // 轮播图
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth/2) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
        _cycleScrollView.delegate = self;
        _cycleScrollView.showPageControl = YES;
        //        _cycleScrollView.pageDotColor = UIColorWithRGB(128, 130, 132);
        //        _cycleScrollView.currentPageDotColor = UIColorWithRGB(173, 36, 36);
        
        _cycleScrollView.pageDotImage = UIImageNamed(@"segmentGray");
        _cycleScrollView.pageControlDotSize = CGSizeMake(rateWidth(15), rateWidth(15));
        _cycleScrollView.currentPageDotImage = UIImageNamed(@"segmentRed");
        
        // 模拟延迟加载
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //            weakSelf.cycleScrollView.imageURLStringsGroup = @[@"http://d.hiphotos.baidu.com/image/pic/item/b7fd5266d016092408d4a5d1dd0735fae7cd3402.jpg",@"http://h.hiphotos.baidu.com/image/h%3D300/sign=2b3e022b262eb938f36d7cf2e56085fe/d0c8a786c9177f3e18d0fdc779cf3bc79e3d5617.jpg",@"http://a.hiphotos.baidu.com/image/pic/item/b7fd5266d01609240bcda2d1dd0735fae7cd340b.jpg",@"http://h.hiphotos.baidu.com/image/pic/item/728da9773912b31b57a6e01f8c18367adab4e13a.jpg",@"http://h.hiphotos.baidu.com/image/pic/item/0d338744ebf81a4c5e4fed03de2a6059242da6fe.jpg"];
            weakSelf.cycleScrollView.imageURLStringsGroup = weakSelf.netImages;
        });
        // 清除缓存
        [self.cycleScrollView clearCache];
    }
    return _cycleScrollView;
}
#pragma mark - 轮播图点击
#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", index);
    
}
- (UICollectionView *)sortCollectionView
{
    if (!_sortCollectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        _sortCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateWidth(200)) collectionViewLayout:layout];
        _sortCollectionView.dataSource = self;
        _sortCollectionView.delegate = self;
        _sortCollectionView.backgroundColor = kClearColor;
        [_sortCollectionView registerClass:[SortCollectionViewCell class] forCellWithReuseIdentifier:@"sortcollectionViewCell"];
        _sortCollectionView.showsVerticalScrollIndicator = NO;
        _sortCollectionView.scrollEnabled = NO;
        
    }
    return _sortCollectionView;
}
- (UICollectionView *)couponCollectionView
{
    if (!_couponCollectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _couponCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateWidth(260)) collectionViewLayout:layout];
        _couponCollectionView.dataSource = self;
        _couponCollectionView.delegate = self;
        _couponCollectionView.backgroundColor = kClearColor;
        [_couponCollectionView registerClass:[HomepageCouponCollectionViewCell class] forCellWithReuseIdentifier:@"couponcollectionViewCell"];
        _couponCollectionView.showsVerticalScrollIndicator = NO;
        _couponCollectionView.showsHorizontalScrollIndicator = NO;
        
    }
    return _couponCollectionView;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight-49-SafeAreaBottomHeight) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = tableViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf getGoodsListData];
            [weakSelf getBannerData];
            [weakSelf getCouponData];
            [weakSelf getUnreadMessage];
        }];
    }
    return _tableView;
}
//获取版本号
-(void)Postpath
{
    NSString *urlStr = [[NSString alloc] initWithFormat:@"http://itunes.apple.com/lookup?id=%@",appId];
    //    https://itunes.apple.com/cn/app/gang-mai-jia/id1179210021?mt=8
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:10];
    
    [request setHTTPMethod:@"POST"];
    
    
    NSOperationQueue *queue = [NSOperationQueue new];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
        NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
        if (data) {
            
            NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) {
                
                [receiveStatusDic setValue:@"1" forKey:@"status"];
                [receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"]   forKey:@"version"];
            } else {
                
                [receiveStatusDic setValue:@"-1" forKey:@"status"];
            }
        }else{
            [receiveStatusDic setValue:@"-1" forKey:@"status"];
        }
        
        [self performSelectorOnMainThread:@selector(receiveData:) withObject:receiveStatusDic waitUntilDone:NO];
    }];
}
-(void)receiveData:(id)sender
{
    NSLog(@"receiveData=%@",sender);
    [self compareVersion:sender[@"version"]];
    
}
- (BOOL)compareVersion:(NSString *)serverVersion{
    
    // 获取应用当前版本号
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    
    /*
     typedef NS_ENUM(NSInteger, NSComparisonResult)
     {
     NSOrderedAscending = -1L,//升序
     NSOrderedSame,   //等于
     NSOrderedDescending  //降序
     };
     */
    
    //比较当前版本和新版本号的大小
    if ([appVersion compare:serverVersion options:NSNumericSearch] == NSOrderedAscending) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"发现新版本" preferredStyle:  UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/app/gang-mai-jia/id%@?mt=8",appId]]];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }]];
        [self presentViewController:alert animated:true completion:nil];
        return YES;
    }else{
        //        K_ALERT(@"没有新版本");
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
